package com.lovi.collection_.set_;

import java.util.HashSet;
import java.util.Objects;

/**
 * 定义一个Employee类，该类包含：private成员属性name,sal,birthday(MyDate类
 * 型),其中birthday为MyDate类型(属性包括: year, month, day),要求:
 * 1.创建3个Employee放入HashSet中
 * 2. 当 name和birthday的值相同时，认为是相同员工，不能添加到HashSet集合中
 */
public class HashSet02 {
	public static void main(String[] args) {
//		MyDate myDate = new MyDate(1999, 12, 12);
//		MyDate myDate2 = new MyDate(1999, 12, 12);
//		System.out.println(myDate.hashCode());
//		System.out.println(myDate2.hashCode());
//		System.out.println(myDate.equals(myDate2));
		HashSet<Employee> set = new HashSet<>();
		set.add(new Employee("jack", 5000, new MyDate(1999, 12, 12)));
		set.add(new Employee("happy", 6000, new MyDate(1999, 12, 12)));
		set.add(new Employee("jack", 7000, new MyDate(1999, 12, 12)));

		for (Employee employee : set) {
			System.out.println(employee);
		}
		/*
		结果：两个
		Employee{name='jack', sal=5000.0, birthday=MyDate{year=1999, month=12, day=12}}
		Employee{name='happy', sal=6000.0, birthday=MyDate{year=1999, month=12, day=12}}
		 */
	}
}
class Employee {
	private String name;
	private double sal;
	private MyDate birthday;
	public Employee(String name, double sal, MyDate birthday) {
		this.name = name;
		this.sal = sal;
		this.birthday = birthday;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (!(o instanceof Employee)) return false;
		Employee employee = (Employee) o;
		return Objects.equals(name, employee.name) && Objects.equals(birthday, employee.birthday);
	}

	@Override
	public int hashCode() {
		return Objects.hash(name, birthday);
	}

	@Override
	public String toString() {
		return "Employee{" +
				"name='" + name + '\'' +
				", sal=" + sal +
				", birthday=" + birthday +
				'}';
	}
}

class MyDate{
	private int year;
	private int month;
	private int day;
	public MyDate(int year,int month,int day){
		this.year = year;
		this.month = month;
		this.day = day;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (!(o instanceof MyDate)) return false;
		MyDate myDate = (MyDate) o;
		return year == myDate.year && month == myDate.month && day == myDate.day;
	}

	/**
	 * 当年月日相同时，返回同样的hashcode
	 * @return
	 */
	@Override
	public int hashCode() {
		return Objects.hash(year, month, day);
	}

	public int getYear() {
		return year;
	}
	public void setYear(int year) {
		this.year = year;
	}
	public int getMonth() {
		return month;
	}
	public void setMonth(int month) {
		this.month = month;
	}
	public int getDay() {
		return day;
	}
	public void setDay(int day) {
		this.day = day;
	}

	@Override
	public String toString() {
		return "MyDate{" +
				"year=" + year +
				", month=" + month +
				", day=" + day +
				'}';
	}
}
